<?php
namespace api\behaviors\actions;

use Yii;
use yii\data\ActiveDataProvider;

/**
 * 重写IndexAction类中的prepareDataProvider方法，支持多个字段排序。
 * @package api\common\actions
 */
class IndexAction extends \yii\rest\IndexAction{


    /**
     * 重写父类prepareDataProvider方法。
     *
     * @return mixed|null|object|\yii\data\DataFilter
     */
    protected function prepareDataProvider()
    {
        $requestParams = Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = Yii::$app->getRequest()->getQueryParams();
        }

        $filter = null;
        if ($this->dataFilter !== null) {
            $this->dataFilter = Yii::createObject($this->dataFilter);
            if ($this->dataFilter->load($requestParams)) {
                $filter = $this->dataFilter->build();
                if ($filter === false) {
                    return $this->dataFilter;
                }
            }
        }

        if ($this->prepareDataProvider !== null) {
            return call_user_func($this->prepareDataProvider, $this, $filter);
        }

        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        $query = $modelClass::find();
        if (!empty($filter)) {
            $query->andWhere($filter);
        }

        // 立即加载
        if ($expand = Yii::$app->request->get('expand')) {
            $expand = explode(',', $expand);
            $query->with($expand);
        }

        return Yii::createObject([
            'class' => ActiveDataProvider::className(),
            'query' => $query,
            'pagination' => [
                'params' => $requestParams,
            ],
            'sort' => [
                'params' => $requestParams,
                'enableMultiSort' => true //允许多个字段排序
            ],
        ]);
    }

}